#!/usr/bin/env python
# encoding:utf-8
'''
@author: yangyongjie
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited. 
@contact: deamoncao100@gmail.com
software: garner
@file: commodityapi.py
@time: 2022/8/29 20:40
@desc:
'''
from flask import Blueprint, request
from flask_restful import Resource, Api
from model.commodity import Commodities
from libs.response import generate_response
from sqlalchemy import or_
from model import db

commodity_bp = Blueprint("commodityapi", __name__, url_prefix="/v1")
api = Api(commodity_bp)

class CommodityView(Resource):
    def get(self, id=None):
        commodity_list = []
        keyword = request.args.get("keyword")
        if keyword is not None:
            commodity_info = Commodities.query.filter(
                or_(Commodities.id.like('%' + keyword + '%'), Commodities.commodity_name.like('%' + keyword + '%'))).all()
        else:
            commodity_info = Commodities.query.all()
        commodity_list += commodity_info
        return generate_response(message="search user success", data=[commodity.to_json() for commodity in commodity_list])


    def post(self, id=None):
        data = request.json
        Commodities.create_commodity(
            commodity_name=data.get("commodity_name"),
            detail=data.get("detail"),
            images=data.get("images"),
            price=data.get("price"),
            stocks=data.get("stocks")
        )
        if True:
            return generate_response(message="add commodity success")

    def put(self, id=None):
        commodity = Commodities.query.get(id)
        if commodity is not None:
            data = request.json
            commodity.commodity_name = data.get("commodity_name")
            commodity.detail = data.get("detail")
            commodity.images = data.get("images")
            commodity.price = data.get("price")
            commodity.stocks = data.get("stocks")
            db.session.add(commodity)
            db.session.commit()
            return generate_response(message="update car succees")
        else:
            return generate_response(status_code=10001, message="commodity doesn't exist")

    def delete(self, id=None):
        result = Commodities.query.get(id)
        if result is not None:
            db.session.delete(result)
            db.session.commit()
            return generate_response(message="delete car success")
        else:
            return generate_response(status_code=10001, message="commodity is not exist")



api.add_resource(CommodityView, "/commodity")
api.add_resource(CommodityView, "/commodity/<int:id>", endpoint="commoditya")

